package Data;

import AppSystem.AppUtils;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import androidx.annotation.Nullable;

import java.io.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

public class SaveFeature {

    public static SharedPreferences.Editor SettingEditor(Context context)
    {
        return context.getSharedPreferences("Setting",Context.MODE_PRIVATE).edit();
    }
    public static SharedPreferences SettingRead(Context context)
    {
        SharedPreferences userInfo = context.getSharedPreferences("Setting", Context.MODE_PRIVATE);
        return userInfo;
    }


    private static final String DataDIR = "/data/data/";

    String getAppDataDir()
    {
        return DataDIR+ AppUtils.getPackageName(context);
    }
    String getAppImageDataDir()
    {
        return  getAppDataDir()+"/ImageData";
    }
    void CreateImageDir()
    {
        File file=new File(getAppImageDataDir());
        if(!file.exists())
        {
            file.mkdir();
        }
    }
    public  Bitmap readImg(String name)
    {
        String dir=getAppImageDataDir()+"/"+name+".jpg";
        File mFile = new File(dir);                        //将要保存的图片文件
        if (!mFile.exists()) {
          return null;
        }
        else
        {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(mFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
           return BitmapFactory.decodeStream(fis);
        }
    }
    public  void DeleteImg(String name)
    {
        String dir=getAppImageDataDir()+"/"+name+".jpg";
        File mFile = new File(dir);
        if(mFile.exists())
        mFile.delete();
    }
    public  boolean saveImg(Bitmap bitmap, String name) {
        try {
            String dir=getAppImageDataDir()+"/"+name+".jpg";
            File mFile = new File(dir);                        //将要保存的图片文件
            if (mFile.exists()) {
                return false;
            }
            FileOutputStream outputStream = new FileOutputStream(mFile);     //构建输出流
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);  //compress到输出outputStream
            return true;

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return false;
    }
    Context context;
    public static Bitmap getBmp(byte[] in)
    {
        if(in==null)
            return null;
        Bitmap bmpout = BitmapFactory.decodeByteArray(in, 0, in.length);
        return bmpout;
    }
    SQLHelper helper;
    public SaveFeature(Context context)
    {
        this.context=context;
        helper=new SQLHelper(context);
        CreateImageDir();
    }
    public void Delete(String id)
    {
        SQLiteDatabase db= helper.getWritableDatabase();
        db.delete(SQLHelper.TableName,SQLHelper.ID+"=?",new String[]{id});
          DeleteImg(id);
          db.close();
    }
    public  boolean Alter(String id,BasicData data)
    {
        if(data!=null&&id!=null)
        {
            Delete(id);
                 return  Add(data);
        }
        else
            return false;

    }

    public BasicData[] Read(int categoryRID)
    {
        String id=context.getString(categoryRID);
        ArrayList<BasicData> arr=new ArrayList<>();
       SQLiteDatabase db= helper.getReadableDatabase();
    Cursor cursor= db.query(SQLHelper.TableName,null,null,null,null,null,null);
    while (cursor.moveToNext()) {

        Date date=null;
        if(!cursor.isNull(cursor.getColumnIndex(SQLHelper.Date)))
        {
            date=StringDealer.strToDateLong(cursor.getString(cursor.getColumnIndex(SQLHelper.Date)));
        }

           BasicData  data=new BasicData( cursor.getString(cursor.getColumnIndex(SQLHelper.Category)),cursor.getInt(cursor.getColumnIndex(SQLHelper.Type)),cursor.getDouble(cursor.getColumnIndex(SQLHelper.Price)),cursor.getString(cursor.getColumnIndex(SQLHelper.Name)),
                    cursor.getString(cursor.getColumnIndex(SQLHelper.Brand)),date,null,cursor.getString(cursor.getColumnIndex(SQLHelper.Tag))
                    );
           if(data.getCategory().equals(id))
           {
               data.setImage(readImg(data.getID()));
               if(data.getDate()!=null)
               {
                   Calendar cal = Calendar.getInstance();
                   cal.setTime(data.getDate());
                   cal.add(Calendar.MONTH,1);
                   data.setDate(cal.getTime());
               }
               arr.add(data);
           }

        }
        BasicData[] res=new BasicData[arr.size()];
        arr.toArray(res);
        db.close();
        return res;
    }

    public boolean  Add(BasicData data)
    {
        if(data!=null)
        {
            ContentValues values = new ContentValues();
            values.put(SQLHelper.ID,data.getID());
            if(data.getDate()!=null)
                values.put(SQLHelper.Date,data.DateStr());
            values.put(SQLHelper.Name,data.getName());
            values.put(SQLHelper.Brand,data.getBrand());
            if(data.getTag()!=null)
                values.put(SQLHelper.Tag,data.getTag());
            values.put(SQLHelper.Type,data.getType());
            if(data.getImage()!=null)
            {
                saveImg(data.getImage(),data.getID());
            }
            values.put(SQLHelper.Price,data.getPrice());
            values.put(SQLHelper.Category,data.getCategory());
            SQLiteDatabase db= helper.getWritableDatabase();
            helper.getWritableDatabase().insert(SQLHelper.TableName,null,values);
            db.close();
            return  true;
        }
        else
            return false;

    }

}
class SQLHelper extends SQLiteOpenHelper
{
    public static final  String DataBaseName="userdata.db";
    public static final  String TableName="info";
    public static final  String ID="ID";
    public static final  String Name="Name";
    public static final  String Brand="Brand";
    public static final  String Date="Date";
    public static final  String Tag="Tag";
    public static final  String Type="Type";
    public static final  String Price="Price";
    public static final  String Category="Category";


    public SQLHelper(@Nullable Context context) {
        super(context,DataBaseName,null,1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String create= "create table info ( `ID` VARCHAR(64) NOT NULL primary key , `Name` VARCHAR(64) NOT NULL , `Category` VARCHAR(64) NOT NULL ,`Brand` VARCHAR(64) NOT NULL , `Date` Date NULL , `Tag` VARCHAR(1024)  NULL , `Type` INT NOT NULL , `Price` DOUBLE NOT NULL);";
        db.execSQL(create);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}